package com.zhou.common.pub.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

/**
 * 获取i18n资源文件
 *
 * @author ruoyi
 */
@Slf4j
public class MessageUtils {
    /**
     * 根据消息键和参数 获取消息 委托给spring messageSource
     *
     * @param code 消息键
     * @param args 参数
     * @return 获取国际化翻译值
     */
    public static String message(String code, Object... args) {
        MessageSource messageSource = null;
        try {
            SpringUtils.getBean(MessageSource.class);
        } catch (Exception e) {
            log.error("获取 MessageSource 失败，", e);
        }
        if (messageSource != null) {
            return messageSource.getMessage(code, args, code, LocaleContextHolder.getLocale());
        } else {
            return code;
        }
    }

    public static String message(String code, String defaultMsg, Object... args) {
        MessageSource messageSource = null;
        try {
            SpringUtils.getBean(MessageSource.class);
        } catch (Exception e) {
            log.error("获取 MessageSource 失败");
        }
        if (messageSource != null) {
            return messageSource.getMessage(code, args, defaultMsg, LocaleContextHolder.getLocale());
        } else {
            return defaultMsg;
        }
    }
}
